
import socket,time, cv2, struct, json
from util_log import timeStart,timeEnd,logger
from util_image import decode


#IP地址'0.0.0.0'为等待客户端连接
ADDRESS = ('0.0.0.0', 9119)
DEBUG = 1

def main():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	#将套接字绑定到地址, 在AF_INET下,以元组（host,port）的形式表示地址.
    sock.bind(ADDRESS)
    
    while 1:
        logger.info("listen.....")
        sock.listen(5)
        def recvall(sock, data_len):
            gap_abs = data_len % 4096
            count = data_len // 4096
            recv_data = b''
            for i in range(count):
                    data = sock.recv(4096, socket.MSG_WAITALL)
                    recv_data += data
            recv_data += sock.recv(gap_abs, socket.MSG_WAITALL)
            return recv_data
        
        #连接则等待有连接
        conn, addr = sock.accept()

        start = time.time()#用于计算帧率data_len信息
            
        ##接收数据
        stringData_rgb=b''
        stringData_depth=b''
        try:
            d = conn.recv(16)
            
            if len(d) < 1:
                continue
            
            print("got header:", d, len(d))
            len1,len2,offsetX,offsetY =  struct.unpack(">LLii", d)
            logger.info('off(x,y):({} {})'.format(offsetX,offsetY))
            logger.info("Get data length image len1:{} image len2:{} data length header:{}".format(len1,len2, len(d)))

            timeStart("image_collect_decode")
            timeStart("time_total_predict")
            stringData_rgb = recvall( conn, len1)
            # stringData_depth = recvall( conn, len2)
        except Exception as msg:
            print(msg)
        logger.info( "Recv data length: %d"%( len(stringData_rgb)))

        if  len(stringData_rgb) == 0:
            continue

        #解码
        decimg_rgb, decimg_depth = decode(stringData_rgb, stringData_depth)
        logger.info("----finish decode image. {}".format(timeEnd("image_collect_decode")))
        ##########################
        
        ##########################
        if DEBUG:
            cv2.imwrite("data.png", decimg_rgb)
        
        final_result = {}
        final_result['image_len']= len1
        feed_back_string = json.dumps(final_result)
        conn.send(feed_back_string.encode())
            

        
    socket.close()
if __name__ == "__main__":
    print("server run with ", ADDRESS)
    main()
